﻿#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfFootball.UI;
using System.Windows.Interop;
using System.Windows.Forms;
using System.Windows.Media.Animation;
using WpfFootball.Parser;
using WpfFootball.Media;
#endregion

namespace WpfFootball
{

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Fields
        private const int WM_DMWCOMPOSITIONCHANGED = 0x031E;
        private const string DEFAULT_TEAM_BUTTON_CONTENT = "Skriv in ditt lag här...";
        private bool requestedManualExit = false;
        private bool deleting = false;

        private DoubleAnimation fadeInAnimation;
        private DoubleAnimation fadeOutAnimation;
        private TimeSpan fadeAnimationLength;
        private IOManager ioManager;
        private TabManager tabManager;
        private static Window window;
        #endregion

        public MainWindow()
        {
            InitilizeWindow();
            window = this;
        }

        /// <summary>
        /// Initiliazes the main window of the application and other needed components.
        /// </summary>
        private void InitilizeWindow()
        {
            InitializeComponent();
            try
            {
                Searcher.Init();
                ioManager = IOManager.Instance();
                tabManager = new TabManager(tabControl1);
                PrepareAnimations();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Gets a reference of this Window object.
        /// </summary>
        public static Window GetWindowRef()
        {
            return window;
        }

        #region Animations
        /// <summary>
        /// Initializes all necesary objects to handle animations.
        /// </summary>
        private void PrepareAnimations()
        {
            fadeInAnimation = new DoubleAnimation();
            fadeOutAnimation = new DoubleAnimation();
            fadeAnimationLength = new TimeSpan(0, 0, 0, 0, 300);
        }

        /// <summary>
        /// Uses an animation to fade-in a control. Fading in a control will also
        /// set the IsEnabled flag of that control to false.
        /// </summary>
        /// <param name="control">The control to apply the fade-in effect on.</param>
        private void FadeInControl(System.Windows.Controls.Control control)
        {
            control.IsEnabled = false;
            fadeInAnimation.From = control.Opacity;
            fadeInAnimation.To = 0;
            fadeInAnimation.Duration = fadeAnimationLength;
            control.BeginAnimation(System.Windows.Controls.Control.OpacityProperty, fadeInAnimation);
        }

        /// <summary>
        /// Uses an animation to fade-out a control. Fading out a control will also
        /// set the isEnabled flag of that control to true.
        /// </summary>
        /// <param name="control">The control to apply the fade-out effect on.</param>
        private void FadeOutControl(System.Windows.Controls.Control control)
        {
            control.IsEnabled = true;
            fadeOutAnimation.From = control.Opacity;
            fadeOutAnimation.To = 1;
            fadeOutAnimation.Duration = fadeAnimationLength;
            control.BeginAnimation(System.Windows.Controls.Control.OpacityProperty, fadeOutAnimation);
        }
        #endregion

        #region Window Handlers
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            GlassHelper.ExtendGlassFrame(this, new Thickness(-1));
            IntPtr hwnd = new WindowInteropHelper(this).Handle;
            HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(WndProc));
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lparam, ref bool handled)
        {
            if (msg == WM_DMWCOMPOSITIONCHANGED)
            {
                GlassHelper.ExtendGlassFrame(this, new Thickness(-1));
                handled = true;
            }
            return IntPtr.Zero;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            tabManager.TemrinateTabs();
            /*if (!requestedManualExit)
            {
                e.Cancel = true;
                this.WindowState = System.Windows.WindowState.Minimized;
            }
            else
            {
                e.Cancel = false;
                requestedManualExit = false;
            }*/
        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            /*if (this.WindowState == System.Windows.WindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                notifyIcon.BalloonTipTitle = "WPF Football minimerad.";
                notifyIcon.BalloonTipText = "Applikationen minimerad.";
                notifyIcon.ShowBalloonTip(400);
                notifyIcon.Visible = true;
            }
            else if (this.WindowState == System.Windows.WindowState.Normal)
            {
                this.ShowInTaskbar = true;
                notifyIcon.Visible = false;
            }*/
        }
        #endregion

        #region Control Handlers
        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //this.DragMove();
        }

        private void exitButton_Click(object sender, RoutedEventArgs e)
        {
            requestedManualExit = true;
            tabManager.TemrinateTabs();
            this.Close();
        }

        private void notifyIcon_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Normal;
        }
        #endregion

        #region Team searcher events
        private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox1.Text) && IsVisible && !deleting)
            {
                string searchWord = textBox1.Text;
                string teamName = Searcher.SearchTeam(searchWord);
                textBox1.Text = teamName;
                textBox1.Select(searchWord.Length, textBox1.Text.Length);
            }
        }

        private void textBox1_GotFocus(object sender, RoutedEventArgs e)
        {
            textBox1.Text = String.Empty;
        }

        private void textBox1_LostFocus(object sender, RoutedEventArgs e)
        {
            if (textBox1.Text.Equals(String.Empty))
            {
                textBox1.Text = DEFAULT_TEAM_BUTTON_CONTENT;
            }
        }

        private void confirmAddButton_Click(object sender, RoutedEventArgs e)
        {
            if (Searcher.TeamNameExists(textBox1.Text) && !Searcher.ManagedTeamExists(textBox1.Text))
            {
                MessageBoxResult dialogResult = MessageManager.ShowConfirmAddNewTeamMessage(textBox1.Text);

                if (dialogResult == MessageBoxResult.Yes)
                {
                    ioManager.AddTeamToManage(textBox1.Text);
                    ioManager.WriteViewSettings(textBox1.Text, ViewKind.FORUM, ViewSettings.GetDefault(ViewKind.FORUM));
                    ioManager.WriteViewSettings(textBox1.Text, ViewKind.NEWS, ViewSettings.GetDefault(ViewKind.NEWS));
                    ioManager.WriteViewSettings(textBox1.Text, ViewKind.FIXTURES, ViewSettings.GetDefault(ViewKind.FIXTURES));

                    tabManager.AddTab(textBox1.Text, true);

                    FadeInControl(textBox1);
                    FadeInControl(confirmAddButton);
                    FadeInControl(cancelButton);
                }
            }
            else
            {
                MessageManager.ShowAddTeamFailedMessage();
            }
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            FadeInControl(textBox1);
            FadeInControl(confirmAddButton);
            FadeInControl(cancelButton);
        }

        private void addTeamButton_Click_1(object sender, RoutedEventArgs e)
        {
            FadeOutControl(textBox1);
            FadeOutControl(confirmAddButton);
            FadeOutControl(cancelButton);
        }

        private void textBox1_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Back)
            {
                deleting = true;
            }
            else if (e.Key == Key.Enter)
            {
                if (!string.IsNullOrEmpty(textBox1.Text))
                {
                    textBox1.CaretIndex = textBox1.Text.Length;
                }
            }
        }

        private void textBox1_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Back)
            {
                deleting = false;
            }
        }
        #endregion
    }
}
